package auctionhaus

import grails.converters.JSON
import org.springframework.mail.*

class NotificationService {
    static exposes = ["jms"]
    static isTopic = false
    def mailService 

    def onMessage(msg) {
       sendEmail(msg)
       return null
    }

    def sendEmail(content) {
        HashMap jsonMAP = JSON.parse(content)
        def winner = jsonMAP.get("winner")
        def seller = jsonMAP.get("seller")
        def subj = jsonMAP.get("subject")
        def message =
                   subj + "\n" +
                   "Name: " + jsonMAP.get("name").toString() + "\n" +
                   "Description: " + jsonMAP.get("description").toString()  + "\n" +
                   "Seller: " + seller + "\n" +
                   "Starting Bid: " + "\$" + jsonMAP.get("startingBid").toString() + "\n" +
                   "Winning Bid: " + "\$" + jsonMAP.get("winningBidAmount").toString() + "\n" +
                   "Number of Bids: " + jsonMAP.get("numberOfBids").toString() + "\n" +
                   "Listing Detail: " + jsonMAP.get("listingDetail").toString()

        try
        {
            if (!winner.isEmpty()) {
                mailService.sendMail {
                    to winner, seller
                    subject subj
                    text (message)
                }
            }
            if (winner.isEmpty())  {
                mailService.sendMail {
                    to seller
                    subject subj
                    text (message)
                }
            }
            return "emailsent"
        }
        catch (MailSendException mse)
        {
         return "emailNotSent"
        }
    }
}
